<?php
# 文件名称:access.php
# MetInfo在线反馈系统 
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
defined( '_SYS' ) or die( 'No direct script access allowed' );
/**
 * 访问权限管理类
 *
 */
class C_access
{
	
	/**
	 * 判断权限
	 *
	 */
	function check($userId, $actionName)
	{
		$userId = (int) $userId;
		$actionName = strtolower(preg_replace('#[\s\-]+#', '.', trim($actionName)));
		static $cache;
		if ($cache == null) {
			$cache = array();
		}
		$cacheId = $userId.'.'.$actionName;
		if (!isset($cache[$cacheId]))
		{
			$sqlUserGroupIds	= null;
			$db = C_loader::getDBO();
			$join = array();
			$where = array();
			$order = array();
			// 所在用户组
			$userGroupIds = $this->getUserGroupMap($userId, true);

			if (!empty($userGroupIds))
			{
				$sqlUserGroupIds = implode(',', $userGroupIds);
				$join[]= ' LEFT JOIN `'.$db->_table_prefix.'usergroup_rule_map` AS ugrm ON ugrm.rule_id = r.id ';
				$join[]= ' LEFT JOIN `'.$db->_table_prefix.'usergroups` AS ug ON ug.id = ugrm.group_id ';
			}
			$where[] = 'r.enabled = 1';
			
			$where[] = 'r.name='. $db->quote($actionName);
			if ($sqlUserGroupIds) {
				$where[] = ' ug.id IN ('. $sqlUserGroupIds .')';
			}
			
			$order[] = 'r.updated_date DESC';			
			
			$join = (count($join) ? implode(' ', $join) : '');
			$where = (count($where) ? ' WHERE '.implode(' AND ', $where) : '');
			$order = (count($order) ? ' ORDER BY '.implode(' ,', $order) : '');
			//是否存在访问关联
			$query = 'SELECT r.id, r.allow, r.return'.
					' FROM `'.$db->_table_prefix.'access_rules` AS r '.
					$join.
					$where.
					$order
					;			
			$db->setQuery( $query, 0, 1);
			$row = $db->loadRow();
			if (is_array($row)) {
				$allow = (isset($row[1]) && $row[1] == 1);
				$cache[$cacheId] = array('rule_id' => $row[0], 'return_value' => $row[2], 'allow' => $allow);
			}
			else {
				$cache[$cacheId] = array('rule_id' => NULL, 'return_value' => NULL, 'allow' => FALSE);
			}
		}
		return $cache[$cacheId]['allow'];
	}

	function getUserGroupMap($userId, $recursive = false)
	{
		$db	= C_loader::getDBO();
		$join = '';
		$select = $recursive ? 'ug2.id' : 'ug1.id';
		$join .= 'LEFT JOIN '.$db->_table_prefix.'usergroups AS ug1 ON ug1.id = uugm.group_id ';
		$join .= $recursive ? 'LEFT JOIN '.$db->_table_prefix.'usergroups AS ug2 ON (ug2.lft >= ug1.lft AND ug2.rgt <= ug1.rgt) ' : '';
		
		$query = 'SELECT '.$select.
				' FROM `'.$db->_table_prefix.'user_usergroup_map` AS uugm '.
				$join.
				' WHERE uugm.user_id = '.(int) $userId
				;
		$db->setQuery($query);
		
		$result = $db->loadResultArray();
		C_loader::helper('array');
		toInteger($result);
		//array_unshift($result, '1');//添加1到结果,当为空时为公共用户组
		return $result;
	}
}
# 本程序是一个开源系统,使用时请你仔细阅读使用协议,商业用途请自觉购买商业授权.
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
?>